<script setup lang="ts">
import { withDefaults, defineProps, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { Delete } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";

interface Props {
  title: string;
  image?: string;
  createdAt: string;
  username: string;
  avatar: string;
  nickname: string;
  id: string;
  showDelete?: boolean;
}

withDefaults(defineProps<Props>(), {
  title: "文章标题",
  image:
    "https://img1.baidu.com/it/u=3811325041,3126978695&fm=253&fmt=auto&app=120&f=JPEG?w=1067&h=800",
  createdAt: new Date().toISOString(),
  username: "",
  avatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
  nickname: "",
  showDelete: false,
});

const emit = defineEmits<{
  (e: "delete", id: string): void;
}>();

const router = useRouter();

const handleClick = (event: Event, id: string) => {
  event.preventDefault();
  router.push(`/home/blog/article/${id}`);
};

const handleDelete = async (event: Event, id: string) => {
  event.stopPropagation();
  try {
    await ElMessageBox.confirm("确定要删除这篇文章吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    emit("delete", id);
  } catch {
    // 用户取消删除
  }
};
</script>

<template>
  <el-card
    class="article-card"
    :body-style="{
      padding: '0px',
      backgroundColor: 'rgba(255, 255, 255, 0.7)',
    }"
    @click="(event) => handleClick(event, id)"
  >
    <template #header>
      <div class="card-header" v-if="showDelete">
        <el-button
          type="danger"
          :icon="Delete"
          circle
          class="delete-button"
          @click="(event) => handleDelete(event, id)"
        />
      </div>
    </template>
    <div class="image-container">
      <el-image :src="image" :alt="title" fit="cover" />
    </div>
    <div class="content">
      <div class="title">
        <span>{{ title }}</span>
      </div>
      <div class="time">
        {{ new Date(createdAt).toLocaleDateString() }}
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.article-card {
  width: 100%;
  transition: transform 0.3s;
  cursor: pointer;

  &:hover {
    transform: translateY(-5px);
  }

  .card-header {
    display: flex;
    justify-content: flex-end;
    padding: 0;
    height: 0;

    .delete-button {
      position: relative;
      top: -20px;
      right: -20px;
      z-index: 1;
      transform: scale(0.8);
    }
  }

  .image-container {
    width: 100%;
    height: 160px;

    .el-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .content {
    padding: 12px;

    .title {
      font-size: 14px;
      font-weight: bold;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 8px;
    }

    .time {
      font-size: 12px;
      color: #999;
    }
  }
}
</style>
